package com.mozai.shopping.service.impl;

import com.mozai.shopping.config.Constant;
import com.mozai.shopping.mapper.UserMapper;
import com.mozai.shopping.pojo.User;
import com.mozai.shopping.pojo.base.BaseResponse;
import com.mozai.shopping.pojo.base.ErrorMessage;
import com.mozai.shopping.pojo.http.UserReq;
import com.mozai.shopping.service.UserService;
import com.mozai.shopping.utils.JWTUtil;
import com.mozai.shopping.utils.MD5Util;
import com.mozai.shopping.utils.bean.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
* @author wj183
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-09-29 08:26:53
*/
@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;

    /**
     * 登录
     * @param request
     * @param response
     * @param userReq
     * @return
     */

    public BaseResponse login(HttpServletRequest request, HttpServletResponse response, UserReq userReq) {
        HttpSession session = request.getSession();
        Token tokenVo = new Token();
        String encryptPassword = MD5Util.encrypt(userReq.getPassword());

        User user = userMapper.selectUser(userReq.getUserName());
        if (user==null){
            return BaseResponse.error(ErrorMessage.LOGIN_NO_USER);
        }
        if (user.getPassword().equals(encryptPassword)){
            Map<String,Object> claims = new HashMap<>();
            claims.put(Constant.SESSION_KEY,user);
            session.setAttribute(Constant.SESSION_KEY,user);
            String token = JWTUtil.generateJwt(claims);
            tokenVo.setToken(token);
            tokenVo.setLoginTime(System.currentTimeMillis());
            tokenVo.setUserId(user.getId());
        }else {
            return BaseResponse.error(ErrorMessage.LOGIN_PASS_ERROR);
        }
        return BaseResponse.ok(tokenVo);
    }
}




